package cn.maihe.elg.operation.web.system;

import cn.maihe.elg.operation.common.Constants;
import cn.maihe.elg.operation.config.ElgConfig;
import cn.maihe.elg.operation.config.ImageUploadConfig;
import cn.maihe.elg.operation.exception.ErrorCode;
import cn.maihe.elg.operation.exception.SystemRuntimeException;
import cn.maihe.elg.operation.model.enums.CustomerAttachmentTypeEnum;
import cn.maihe.elg.operation.model.enums.UserStatusEnum;
import cn.maihe.elg.operation.model.enums.UserType;
import cn.maihe.elg.operation.model.vo.system.*;
import cn.maihe.elg.operation.repository.entity.BidCustomerDO;
import cn.maihe.elg.operation.repository.entity.CustomerAttachmentDO;
import cn.maihe.elg.operation.repository.entity.SmsDO;
import cn.maihe.elg.operation.repository.entity.UserDO;
import cn.maihe.elg.operation.service.business.BidCustomerService;
import cn.maihe.elg.operation.service.system.OrganizationService;
import cn.maihe.elg.operation.service.system.SmsService;
import cn.maihe.elg.operation.service.system.UserService;
import cn.maihe.elg.operation.supports.ocr.AliyunOcrService;
import cn.maihe.elg.operation.utils.Base64Util;
import cn.maihe.elg.operation.utils.IdGenerate;
import cn.maihe.elg.operation.utils.OrgCodeHandler;
import com.alibaba.cloudapi.sdk.model.ApiResponse;
import com.alibaba.fastjson.JSONObject;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*;

/**
 * @author JHWei
 * @date 2018/3/18
 */
@RestController
@Api(value = "用户注册接口", tags = {"用户注册管理"})
@Slf4j
public class RegistController {

    @Resource
    private AliyunOcrService aliyunOcrService;
    @Resource
    private BidCustomerService bidCustomerService;
    @Resource
    private UserService userService;
    @Resource
    private SmsService smsService;

    @Resource
    private OrgCodeHandler orgCodeHandler;

    @Resource
    private ElgConfig elgConfig;
    @Resource
    private OrganizationService organizationService;
    @Resource
    private ImageUploadConfig imageUploadConfig;
    @Value("${cn.maihe.elg.aliyun.sms.sms-flag:0}")
    private int smsFlag;



    @RequestMapping(value = "/api/regist/upload/image", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "上传图片,文件不能为空，大小不能超过10M")
    public String uploadImage(@RequestParam("file") MultipartFile file) {

        if (file.isEmpty()) {
            throw new SystemRuntimeException(ErrorCode.BSMAU004);
        }
        if (file.getSize() > imageUploadConfig.getMaxSize()) {
            throw new SystemRuntimeException(ErrorCode.BSMAU005);
        }

        String fileName = file.getOriginalFilename();
        String fileExt = fileName.substring(fileName.lastIndexOf(".")+1);
        fileExt = fileExt.toLowerCase();
        if (!imageUploadConfig.getType().contains(fileExt)) {
            throw  new SystemRuntimeException(ErrorCode.BSMAU006, fileExt);
        }
        // 生成一个随机的名称，避免文件名重复
        UUID uuid = UUID.randomUUID();
        Path registDir = Paths.get(imageUploadConfig.getPath()+Constants.REGIST_IMAGE_PATH);
        if(Files.notExists(registDir)){
            try {
                Files.createDirectories(registDir);
            } catch (IOException e) {
                log.error("创建注册目录异常",e);
                throw  new SystemRuntimeException(ErrorCode.ERROR, "创建注册目录失败");
            }
        }
        // 保存文件
        try {
            File saveFile = registDir.resolve(uuid + "." + fileExt).toFile();
            file.transferTo(saveFile);
        } catch (IOException e) {
            log.error("上传失败",e);
            throw new SystemRuntimeException(ErrorCode.BSMAU007);
        }

        return  uuid +"."+ fileExt;
    }


    @ApiOperation(value = "ocr接口", notes = "ocr信息")
    @RequestMapping(value = "/api/regist/ocr", method = RequestMethod.POST)
    public OcrRespDTO ocr(@Validated @RequestBody OcrReqDTO ocrReqDTO) {
        //todo
        String imageBase64 = Base64Util.img_base64(imageUploadConfig.getPath()+ Constants.REGIST_IMAGE_PATH+ocrReqDTO.getImage());

        OcrRespDTO respDTO = new OcrRespDTO();
        ApiResponse apiResponse =  aliyunOcrService.ocr(ocrReqDTO.getType(),imageBase64);
        log.info("ocr return:{}", JSONObject.toJSONString(apiResponse));
        respDTO.setCode(apiResponse.getCode()+"");
        respDTO.setMsg(apiResponse.getMessage());
        if(apiResponse.getCode() != 200){
            List<String> messages = apiResponse.getHeaders().get("X-Ca-Error-Message");
            if(messages!=null&&messages.size()>0){
                respDTO.setMsg(messages.get(0));
            }
        }
        respDTO.setContent(new String(apiResponse.getBody()));
        return respDTO;
    }

    @ApiOperation(value = "注册接口手机验证码发送", notes = "注册接口")
    @RequestMapping(value = "/api/regist/sendSms", method = RequestMethod.POST)
    public SendSmsRespDTO sendSms(@Validated @RequestBody SendSmsDTO sendSmsDTO){
        SendSmsRespDTO respDTO = new SendSmsRespDTO();
        // 检测用户是否已经存在
        // 检查短信发送次数
        // 发送短信入库
        UserDO user = userService.getByUsername(sendSmsDTO.getMobile());
        if(user!=null){
            //
            respDTO.setStatus("FAIL");
            respDTO.setMsg("该手机号用户已存在");
            return respDTO;
        }
        if(smsService.getMobileCount(sendSmsDTO.getMobile())>3){
            respDTO.setStatus("FAIL");
            respDTO.setMsg("请勿频繁发送");
            return respDTO;
        }

        StringBuffer text = new StringBuffer();
        Random rand = new Random();
        for(int i = 0; i < 4; ++i) {
            text.append(rand.nextInt(10));
        }

        SmsDO smsDO = new SmsDO();
        smsDO.setCode(text.toString());
        smsDO.setCreateTime(new Date());
        smsDO.setEvent(sendSmsDTO.getEvent());
        smsDO.setMobile(sendSmsDTO.getMobile());
        smsDO.setSmsType(1);
        smsDO.setTimes(0);
        smsDO.setId(IdGenerate.getId());

        respDTO = smsService.sendSms(smsDO);

        return respDTO;
    }

    @ApiOperation(value = "注册接口手机验证码验证", notes = "注册接口")
    @RequestMapping(value = "/api/regist/checkCode", method = RequestMethod.POST)
    public SendSmsRespDTO sendSms(@Validated @RequestBody SmsCodeCheckDTO smsCodeCheckDTO){
        if(smsFlag==1){
            return smsService.checkSmsCode(smsCodeCheckDTO.getMobile(),smsCodeCheckDTO.getCode());
        }
        SendSmsRespDTO respDTO = new SendSmsRespDTO();
        UserDO user = userService.getByUsername(smsCodeCheckDTO.getMobile());
        if(user!=null){
            //
            respDTO.setStatus("FAIL");
            respDTO.setMsg("该手机号用户已存在");
            return respDTO;
        }
        respDTO.setStatus("SUC");
        respDTO.setMsg("");
        return respDTO;
    }

    @ApiOperation(value = "注册接口", notes = "注册接口")
    @RequestMapping(value = "/api/regist/create", method = RequestMethod.POST)
    public void regist(@Validated @RequestBody RegistReqDTO registReqDTO){
        BidCustomerDO bidCustomerDO = new BidCustomerDO();
        UserDO user = new UserDO();
        BeanUtils.copyProperties(registReqDTO,bidCustomerDO);
        user.setUsername(registReqDTO.getUsername());
        user.setName(StringUtils.isNoneEmpty(registReqDTO.getBidderContactName())?registReqDTO.getBidderContactName():registReqDTO.getBidderName());
        user.setMobileNo(registReqDTO.getBidderContactTel());
        user.setEmail(registReqDTO.getBidderEamil());
        user.setPassword(registReqDTO.getPassword());
        user.setOrgCode("-1");
        user.setType(UserType.BIDDER.getType());
        user.setStatus(UserStatusEnum.NORMAL.toString());
        bidCustomerDO.setId(IdGenerate.getId());
        List<CustomerAttachmentDO> customerAttachmentDOS = new ArrayList<>();
        CustomerAttachmentDO businessLicenseAttach = setCustomerAttachment(
                bidCustomerDO.getId(), CustomerAttachmentTypeEnum.TYPE_0.getType(), registReqDTO.getBusinessLicensePic());
        customerAttachmentDOS.add(businessLicenseAttach);
        CustomerAttachmentDO accountOpenLicenseAttach = setCustomerAttachment(
                bidCustomerDO.getId(), CustomerAttachmentTypeEnum.TYPE_1.getType(), registReqDTO.getAccountOpenLicensePic());
        customerAttachmentDOS.add(accountOpenLicenseAttach);
        CustomerAttachmentDO legalIdcardAttach = setCustomerAttachment(
                bidCustomerDO.getId(), CustomerAttachmentTypeEnum.TYPE_2.getType(), registReqDTO.getLegalIdcardPic());
        customerAttachmentDOS.add(legalIdcardAttach);
        CustomerAttachmentDO legalIdcard1Attach = setCustomerAttachment(
                bidCustomerDO.getId(), CustomerAttachmentTypeEnum.TYPE_3.getType(), registReqDTO.getLegalIdcard1Pic());
        customerAttachmentDOS.add(legalIdcard1Attach);
        CustomerAttachmentDO ApplyAttach = setCustomerAttachment(
                bidCustomerDO.getId(), CustomerAttachmentTypeEnum.TYPE_4.getType(), registReqDTO.getApplyPic());
        customerAttachmentDOS.add(ApplyAttach);
        CustomerAttachmentDO contactAttach = setCustomerAttachment(
                bidCustomerDO.getId(), CustomerAttachmentTypeEnum.TYPE_5.getType(), registReqDTO.getContactPic());
        customerAttachmentDOS.add(contactAttach);
        CustomerAttachmentDO authAttach = setCustomerAttachment(
                bidCustomerDO.getId(), CustomerAttachmentTypeEnum.TYPE_6.getType(), registReqDTO.getAuthPic());
        customerAttachmentDOS.add(authAttach);

        bidCustomerService.regist(bidCustomerDO,user,customerAttachmentDOS);
    }


    @ApiOperation(value = "登录手机验证码发送", notes = "注册接口")
    @RequestMapping(value = "/api/auth/sendSms", method = RequestMethod.POST)
    public SendSmsRespDTO sendCodeSms(@Validated @RequestBody SendSmsDTO sendSmsDTO){
        SendSmsRespDTO respDTO = new SendSmsRespDTO();
        // 检测用户是否已经存在
        // 检查短信发送次数
        // 发送短信入库
        UserDO user = userService.getByUsername(sendSmsDTO.getMobile());
        if(user==null){
            //
            respDTO.setStatus("FAIL");
            respDTO.setMsg("该手机号用户不存在");
            return respDTO;
        }
        if(smsService.getMobileCount(sendSmsDTO.getMobile())>3){
            respDTO.setStatus("FAIL");
            respDTO.setMsg("请勿频繁发送");
            return respDTO;
        }

        StringBuffer text = new StringBuffer();
        Random rand = new Random();
        for(int i = 0; i < 4; ++i) {
            text.append(rand.nextInt(10));
        }

        SmsDO smsDO = new SmsDO();
        smsDO.setCode(text.toString());
        smsDO.setCreateTime(new Date());
        smsDO.setEvent(sendSmsDTO.getEvent());
        smsDO.setMobile(sendSmsDTO.getMobile());
        smsDO.setSmsType(1);
        smsDO.setTimes(0);
        smsDO.setId(IdGenerate.getId());

        respDTO = smsService.sendSms(smsDO);

        return respDTO;
    }


    private CustomerAttachmentDO setCustomerAttachment(Long bidderId,String attachType,String fileName){
        CustomerAttachmentDO customerAttachmentDO = new CustomerAttachmentDO();
        customerAttachmentDO.setId(IdGenerate.getId());
        customerAttachmentDO.setBidderId(bidderId);
        customerAttachmentDO.setAttachType(attachType);
        customerAttachmentDO.setAttachPath(fileName);
        customerAttachmentDO.setAttachFileName(fileName);
        return  customerAttachmentDO;
    }
}
